express = require 'express'
router = express.Router()

http = require 'http'

BufferHelper = require 'bufferhelper'
iconv = require 'iconv-lite'

router.get '/',(req,res,next)->
	console.log req.cookies
	if req.session.user?
		if req.session.type = 't'
			res.redirect '/teacher'
		else if req.session.type = 's'
			res.redirect '/student'
		else
			req.session.user = null
			req.session.type = null
			next()
	else
		next()

router.post '/',(req,res)->
	console.log req
	res.end()

router.get '/',(req,res)->
	res.render 'index',{title:'student signup system'}


router.get '/test',(req,res)->
	if not req.cookies.iPlanetDirectoryPro?
		res.redirect 'http://ids1.tjcu.edu.cn/amserver/UI/Login?goto=http://checkin.tjcu.edu.cn/'
	else
		buffer = new BufferHelper()
		url = "http://my.tjcu.edu.cn/ids_sso.jsp?method=getImUser&wParam=#{req.cookies.iPlanetDirectoryPro}"
		console.log url
		http.get url,(rs)->
			rs.on 'data',(data)->
				buffer.concat data
			rs.on 'end',()->
				html = iconv.decode(buffer.toBuffer(),"GBK")
				console.log html

router.get '/err',(req,res)->
	if !req.session.err
		res.redirect('/')
	else
		req.render 'err',{'err':req.session.err}
		req.session.err = null



module.exports = router
